# -*- coding: utf-8 -*-
__author__ = 'Paul'
import random
from zope import schema
from zope.formlib import form
from zope.interface import implements
from zope.component import getMultiAdapter
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import\
    ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Products.bpContents import _
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from Acquisition import aq_inner
from plone.memoize.compress import xhtml_compress
from Products.bpContents.aviso import IAviso
from Products.ATContentTypes.interfaces import IATDocument
from Products.bpContents.galeria import IGaleria
from zope.site.hooks import getSite
from OFS.interfaces import IOrderedContainer
import unicodedata


class ISalasPortlets(IPortletDataProvider):
    count = schema.Int(title=_(u'Number of items to display'),
        description=_(u'How many items to list.'),
        required=True,
        default=3)



class Assignment(base.Assignment):
    implements(ISalasPortlets)

    def __init__(self, count=5,canal=[], categoria=[]):
        self.count = count

    @property
    def title(self):
        return _(u"Salas Museo")

class Renderer(base.Renderer):
    render = ViewPageTemplateFile('salas_portlets.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        plone_tools = getMultiAdapter((context, self.request), name=u'plone_tools')
        self.atvm = getToolByName(context , 'portal_vocabularies')
        self.catalog = plone_tools.catalog()
        self.anonymous = portal_state.anonymous()
        self.portal_url = portal_state.portal_url()


    @property
    def available(self):
        return True
        #len(self._data())>0

    def getRamas(self):
        return self._data()

    def _data(self):
        ramas=[]


        # you know some object which is refered as "context"

        portal = self.context.portal_url.getPortalObject()
        baseObje=portal["home"]["galerias"]
        rutaBase="/".join(baseObje.getPhysicalPath())
        catalogo=self.catalog({'object_provides': IGaleria.__identifier__,'path': {'query': rutaBase, 'depth': 1}})
        flagRama=0

        for ramaIndice in catalogo:
            ramaObj=baseObje.unrestrictedTraverse(ramaIndice.getPath())

            if ramaObj.tipoGaleria!="Multimedia":
                rama=ramaIndice
                flagItem=0

                if ramaObj.nombre:
                    tituloSala = ramaObj.nombre
                else:
                    tituloSala=ramaObj.Title()
                resumen=ramaIndice.Description
                if len(resumen)>60:
                    resumen=resumen[:ramaIndice.Description[:60].rfind(" ")]+" ..."


                objRama=dict()
                objRama['titulo']="Sala "+tituloSala
                objRama['descri']=resumen

                if hasattr(ramaObj.retrato,"filename"):
                    objRama['retrato']=True
                else:
                    objRama['retrato']=False

                objRama["url"]=ramaIndice.getPath()
                objRama['position']=self.get_position_in_parent(ramaObj)
                ramas.append(objRama)


        return sorted(ramas)

    def get_position_in_parent(self,obj):
        """ Use IOrderedContainer interface to extract the object's manual ordering position
        """
        parent = obj.aq_inner.aq_parent
        ordered = IOrderedContainer(parent, None)
        if ordered is not None:
            return ordered.getObjectPosition(obj.getId())
        return 0



class AddForm(base.AddForm):
    form_fields = form.Fields(ISalasPortlets)
    label = _(u"Add Recent Portlet")
    description = _(u"This portlet displays recently modified content.")

    def create(self, data):
        return Assignment(count=data.get('count', 3))

class EditForm(base.EditForm):
    form_fields = form.Fields(ISalasPortlets)
    label = _(u"Edit Recent Portlet")
    description = _(u"This portlet displays recently modified content.")